<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    title="设备选择"
    :destroy-on-close="true"
    draggable
    :align-center="true"
    style="max-width: 900px; height: 500px"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="90"
      style="width: 100%"
      :rules="rules"
    >
      <div class="mb-[10px]">
        <el-button type="success" @click="addRow"
          ><i-ep-plus />新增行</el-button
        >
      </div>

      <el-table
        ref="dataTableRef"
        :data="formData.listEquipment"
        highlight-current-row
        border
        :cell-style="{ 'text-align': 'center' }"
        style="height: 280px"
      >
        <el-table-column
          label="加工顺序"
          align="center"
          prop="workSequence"
          width="120"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listEquipment.' + scope.$index + '.workSequence'"
              :rules="rules.workSequence"
            >
              <el-input-number
                v-model="scope.row.workSequence"
                :controls="false"
                style="width: 100%"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="工作中心"
          align="center"
          prop="workCenterCode"
          min-width="150"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ scope.row.workCenterCode }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="设备编号"
          align="center"
          prop="equipmentCode"
          min-width="150"
        >
          <template #default="scope">
            <el-form-item
              label-width="1"
              :prop="'listEquipment.' + scope.$index + '.equipmentId'"
              :rules="rules.equipmentId"
            >
              <el-select
                v-model="scope.row.equipmentId"
                placeholder="设备编号"
                clearable
                @change="changeEquipment(scope.row)"
                style="width: 100%"
              >
                <el-option
                  v-for="item in equipmentList"
                  :key="item.id"
                  :label="`${item.equipCode}-${item.equipName}`"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="设备描述"
          align="center"
          prop="remarks"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1">
              {{ scope.row.remarks }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="设备类型"
          align="center"
          prop="equipTypeName"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              {{ scope.row.equipTypeName }}
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="无人设备"
          align="center"
          prop="isUnmannedEquip"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              <el-switch
                v-model="scope.row.isUnmannedEquip"
                inline-prompt
                :active-value="1"
                :inactive-value="0"
                active-text="是"
                inactive-text="否"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          prop="action"
          min-width="100"
        >
          <template #default="scope">
            <el-form-item label-width="1" class="equip-form-item">
              <el-button
                type="primary"
                size="small"
                link
                @click="removeRow(scope.row)"
              >
                删除
              </el-button>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import useEvent from "@/utils/useEvent";
import { productionVersionHook } from "@/views/mes/produceVersion/hook/productionVersionHook";
import request from "@/utils/request";

const { eventBusEmit, eventBusOn } = useEvent();
const { event, api, validateInt } = productionVersionHook();
defineOptions({
  name: "DAYPLANPRODUCTIONVERSIONEQUIPDIALOG",
  inheritAttrs: false,
});
const visibleDialog = ref(false);

const rowData = ref(null);

const formRef = ref(null);

const processCodeStr = ref("");

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);
watch(
  () => props.data,
  async (row: any) => {
    rowData.value = row;
    const { processCode, processName } = row;
    processCodeStr.value = processCode + "-" + processName;
    formData.listEquipment = row.listEquipment
      ? JSON.parse(JSON.stringify(row.listEquipment))
      : [];
    await getEquipmentList();
    formData.listEquipment?.forEach((item) => {
      item.workCenterCode = rowData.value.workCenterCode;
      changeEquipment(item);
    });
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

const addRow = () => {
  formData.listEquipment.push({
    produceVersionProcessId: rowData.value.produceVersionProcessId,
    workSequence: 0,
    workCenterCode: rowData.value.workCenterCode,
    equipmentName: "",
    equipmentCode: "",
    equipmentId: "",
  });
};

const removeRow = (row) => {
  const indexOf = formData.listEquipment.indexOf(row);
  formData.listEquipment.splice(indexOf, 1);
  formRef.value.validate();
};

onMounted(() => {
  // eventBusOn(event.equip, async (row) => {
  //   visibleDialog.value = true;
  //   rowData.value = row;
  //   const { processCode, processName } = row;
  //   processCodeStr.value = processCode + "-" + processName;
  //   formData.listEquipment = row.listEquipment
  //     ? JSON.parse(JSON.stringify(row.listEquipment))
  //     : [];
  //   await getEquipmentList();
  //   formData.listEquipment?.forEach((item) => {
  //     item.workCenterCode = rowData.value.workCenterCode;
  //     changeEquipment(item);
  //   });
  // });
});
const formData = reactive({
  listEquipment: [],
});

const changeEquipment = (row) => {
  const find = equipmentList.value.find((item) => item.id === row.equipmentId);
  row.remarks = find?.remarks;
  row.equipmentCode = find?.equipCode;
  row.equipmentName = find?.equipName;
  row.equipTypeName = find?.equipTypeName;
  row.isUnmannedEquip = find?.isUnmannedEquip;
};

const equipmentList = ref([]);

const getEquipmentList = async () => {
  const { data } = await request({
    url: api.getEquipmentList,
    method: "post",
    data: {
      workCenterId: rowData.value.workCenterId,
    },
  });
  equipmentList.value = data;
};

const resetForm = () => {
  formData.listEquipment = [];
  rowData.value = null;
  processCodeStr.value = "";
};

const validateEquip = (rule, value) => {
  const filter = formData.listEquipment.filter(
    (item) => item.equipmentId === value
  );
  if (filter.length > 1) {
    return Promise.reject("设备已存在");
  }
  return Promise.resolve();
};

const submit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      rowData.value.listEquipment = formData.listEquipment;
      // eventBusEmit(event.workerSubmit);
      closeDialog();
    }
  });
};
const rules = {
  workSequence: [
    {
      required: true,
      message: "请输入加工顺序",
      trigger: ["blur", "change"],
    },
    {
      validator: validateInt,
      trigger: ["blur", "change"],
    },
  ],
  equipmentId: [
    {
      required: true,
      message: "请选择设备",
      trigger: ["blur", "change"],
    },
    {
      validator: validateEquip,
      trigger: ["blur", "change"],
    },
  ],
};
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
